<?php

namespace app\admin\controller\base;

use app\common\controller\Backend;
use app\index\controller\Toolposter;
use app\index\controller\Tool;
/**
 * 来源管理
 *
 * @icon fa fa-circle-o
 */
class Source extends Backend
{
    
    /**
     * Source模型对象
     * @var \app\admin\model\base\Source
     */
    protected $model = null;
     protected $searchFields = 'id,name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\base\Source;
        $this->view->assign("typeList", $this->model->getTypeList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
     /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
             
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                            $data = [];
                            $this->Tool = new Tool();
                            $data['erweima_url'] =  $this->Tool->make($params['type'],$this->model->id);
                            $data['url'] =  str_replace("xxx",$this->model->id,GetBaseInfo('Tool')['Source'][$params['type']]['url']);
                            $this->Toolposter = new Toolposter();
                            $resut = $this->Toolposter->watermark(['type'=>GetBaseInfo('Tool')['Source'][$params['type']]['hb_type'],'erweima'=>$data['erweima_url']]);
                            if($resut['true'] == 1){
                              $data['poster_url'] = $resut['data'];
                            }
                            $send_show = $this->model->where(['id'=>$this->model->id])->update($data);
                        if($send_show){
                             $this->success();
                        }else{
                             $this->error($this->model->getError());
                        }
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    if(!$row['erweima_url']){
                       $this->Tool = new Tool();
                        $params['erweima_url'] =  $this->Tool->make($params['type'],$ids);
                        $params['url'] =  str_replace("xxx",$ids,GetBaseInfo('Tool')['Source'][$params['type']]['url']);
                        $this->Toolposter = new Toolposter();
                        $resut = $this->Toolposter->watermark(['type'=>GetBaseInfo('Tool')['Source'][$params['type']]['hb_type'],'erweima'=>$params['erweima_url']]);
                        if($resut['true'] == 1){
                          $params['poster_url'] = $resut['data'];
                        }
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
     /**
     * 导入
     */
    public function import()
    {
        print_r(111111);die;
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }
 
        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        $this->Tool = new Tool();
        $this->Toolposter = new Toolposter();
        $insert = [];
        $i = 16;
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : $val;
            }
            $row = [];
            $temp = array_combine($fields, $values);
            foreach ($temp as $k => $v) {
                if (isset($fieldArr[$k]) && $k !== '') {
                    $row[$fieldArr[$k]] = $v;
                }
            }

            if ($row) {
                //$row['order'] = date('H:i:s',\PHPExcel_Shared_Date::ExcelToPHP($row['order']));
                $row['publish']  = $row['z_publish']  = 1; 
                $row['url'] =  str_replace("xxx",$i,GetBaseInfo('Tool')['Source'][$row['type']]['url']);;
                //$row['erweima_url'] = $this->Tool->make($row['type'],$i);
                //$resut = $this->Toolposter->watermark(['type'=>GetBaseInfo('Tool')['Source'][$row['type']]['hb_type'],'erweima'=>$row['erweima_url']]);
                //$row['poster_url'] = $resut['data'];
                $insert[] = $row;
            }
            $i++;
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
        try {
            $this->model->saveAll($insert);
        } catch (\think\exception\PDOException $exception) {
            $this->error($exception->getMessage());
        }

        $this->success();
    }

}
